Leetcode:49. Group Anagrams
问题的描述为: Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase. The order of your output does not matter.
思路:
关键在于,有相同字符确定的不同字符串怎么的确定?
如果把hashcode变成字母的和,是不是直接的判断hashcode的值就行了?
转念在一想不行,例如:duh, ill 值是相同的,
所以我们可以采用26个特殊的值,它们相加的时候,和自己的有关,
这个设计到质数的概念,计算出26个质数,这个比较的困难!
确定一中唯一的比对规则很重要。
具体的代码:
public static List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return null;
}
Map<String, List<String>> judge = new HashMap<String, List<String>>();
for (String key : strs) {
char[] value = key.toCharArray();
Arrays.sort(value);
String tmp1 = new String(value);
if (!judge.containsKey(tmp1)) judge.put(tmp1, new ArrayList<String>());
judge.get(tmp1).add(key);
}
return new ArrayList<List<String>>(judge.values());
}